import Taro from '@tarojs/taro';
import short from 'short-uuid'

let initPromise;

const WX_CLOUD_ENV = "test-3gn19zzu8e55661f";

export function initRequest() {
  initPromise = wx.cloud.init();
  return initPromise;
}

export async function request(
  path: string,
  method: string,
  data: any
): Promise<any> {
  try {
    const res = await wx.cloud.callContainer({
      config: {
        env: WX_CLOUD_ENV, // 微信云托管的环境ID
      },
      path: path, // 填入业务自定义路径和参数，根目录，就是 /
      method: method, // 按照自己的业务开发，选择对应的方法
      header: {
        "X-WX-SERVICE": "formula-help-service", // xxx中填入服务名称（微信云托管 - 服务管理 - 服务列表 - 服务名称）
        // 其他header参数
      },
      data,
    });

    const resData = res.data

    if (resData.code !== 0 && resData.message) {
      Taro.showToast({
        title: resData.message,
        icon: "none",
      })

      if (resData.code === 10005 || resData.code === 10006 || resData.code === 10007) {
        Taro.redirectTo({
          url: '/pages/apply/index'
        })
      }

      throw res.data
    }

    return resData;
  } catch (e) {
    throw e;
  }
}

request.get = (path: string, data?: any) => request(path, "GET", data);
request.post = (path: string, data?: any) => request(path, "POST", data);
request.put = (path: string, data?: any) => request(path, "PUT", data);
request.delete = (path: string, data?: any) => request(path, "DELETE", data);

export function uploadFile(localUrl: string, cloudDir: string) {
  const ext = localUrl.split('.').pop()
  const fileName = `${short.generate()}.${ext}`
  return wx.cloud.uploadFile({
    cloudPath: `${cloudDir}/${fileName}`, // 对象存储路径，根路径直接填文件名，文件夹例子 test/文件名，不要 / 开头
    filePath: localUrl, // 微信本地文件，通过选择图片，聊天文件等接口获取
    config: {
      env: WX_CLOUD_ENV // 需要替换成自己的微信云托管环境ID
    }
  }).then(res => {
    return res.fileID
  }).catch(err => {
    console.error(err)
    return Promise.reject(err)
  })  
}


export function uploadAvatar(localUrl: string) {
  return uploadFile(localUrl, 'avatars')
}

export function uploadFoodImage(localUrl: string) {
  return uploadFile(localUrl, 'foods')
}
